package com.xjh.serverinspect.security.advice;

import com.xjh.serverinspect.security.RequestBodyHandler;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;

/**
 * <p>
 * 请求参数解密
 * </p>
 *
 * @author XuJinghui
 * @since 2024/3/7
 */
@RestControllerAdvice
public class RequestBodyDecodeAdvice extends RequestBodyAdviceAdapter {

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> clazz) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        // 获取加密的AES密钥
        List<String> headers = inputMessage.getHeaders().get("X-Encrypt");

        // 强制请求参数需加密
        if (headers == null || headers.isEmpty())
            throw new RuntimeException("缺失请求头X-Encrypt");

        try {
            return new HttpInputMessage() {
                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }

                @Override
                public InputStream getBody() {
                    return new ByteArrayInputStream(RequestBodyHandler.decrypt(inputMessage));
                }
            };
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
